<?
/**
 * VoiceOne Settings/Queues/edit
 *
 * Frontend to provide access to the queue system in voiceone.
 * @package voiceone
 * @subpackage  settings_queues
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  sajax_init();
  
  //================ XAJAX ================
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $agent=$formData["agent"];
    $client=$agent["client"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //Client not null
    $clientErr=false;
    if(($client==0)||($client=="")){
    	//name cannot be null
      $errOut[]= T_("Agent must be linked to an application");
      $objResponse->addAssign("clientErr","innerHTML",$imgErr);
      $clientErr=true;  
    }
    if($clientErr===false) $objResponse->addAssign("clientErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML",""); 
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    $agent=$_POST["agent"];
    $entry=array(
      "id" => $agent["id"],
      "client" => $agent["client"],
      "extension" => $agent["extension"],
      "username" => $agent["username"],
      "password" => $agent["password"]
    );
    $joinArr=array();
    if((is_array($agent["joined_queues_id"]))&&(is_array($agent["joined_queues_penalty"]))){
    	for($i=0;$i<count($agent["joined_queues_id"]);$i++){
     		$joinArr[]=array(
        		"id" => $agent["joined_queues_id"][$i],
            "penalty" => $agent["joined_queues_penalty"][$i]
        	);
      }
    }
    $entry["joined_queues"]=$joinArr;
    //put Agent
    $ret=$asterisk->putAgent($entry);
    if ($ret>0) {
      $alert="<div class=\"AlertGood\">".T_("The agent has been modified")."</div>";
      $_GET["id"]=$ret;
    } else $alert="<div class=\"AlertBad\">".T_("The agent hasn't been modified")."</div>";
    goToMainPage($alert);
  }
  //================ PAGE LOGIC ================
  //retrieve the agent informations
  if ($_GET["id"]!="") {
    $ret=$asterisk->getAgent($_GET["id"]);
    $agent=$ret[0];
    if(!is_array($agent)) die();
  	$id=$agent["id"];
    $client=$agent["client"];
    $extension=$agent["extension"];
    $username=$agent["username"];
    $password=$agent["password"];
    $joined_queues=$agent["joined_queues"];
    $title=sprintf(T_("Modify agent %1\$s"),$queueName );  
  }else{
    $title=T_("New agent");
  }
  //get applications
	$appOpt.="<option value=\"0\">[none]</option>";
  $appScript="var appArr=new Array();\n ";
	$appScript.="appArr[0]='';\n ";
  $ret=$asterisk->getAgent(0);
  if(is_array($ret)){
  	foreach($ret as $a){
  		$allAgentArr[]=$a["client"];
    }
  }
  $ret=$asterisk->getApplication(0);
  if(is_array($ret)){
  	foreach($ret as $app){
    	$app_id=$app["id"];
      $app_extension=$app["extension"];
      $app_name=$app["label"];
      //disable application already linked to an agent
      if(($client!=$app_id)&&(is_array($allAgentArr))&&(in_array($app_id,$allAgentArr,true))) $disabled="disabled=\"disabled\""; else $disabled="";
      //select application matching with passed id
      if($client==$app_id) $s="selected=\"selected\""; else $s="";
      //set html
    	$appOpt.="<option value=\"".$app_id."\" $s $disabled>".$app_name."</option>";
      //set javasript array
      $appScript.="appArr['".$app_id."']='".$app_extension."';\n ";
    }
  }
  //set hidden for joined queues
  $joined_html="";
  if(is_array($joined_queues)){
  	foreach($joined_queues as $q){
  		$joined_html.="<input type=\"hidden\" name=\"agent[joined_queues_id][]\" value=\"".$q["id"]."\" />".
      					"<input type=\"hidden\" name=\"agent[joined_queues_penalty][]\" value=\"".$q["penalty"]."\" />";
    }
  }
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");
  ?>
  <script><?=$appScript?></script>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin" ><?=T_("Return without save")?></a> 
    </h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post">
      <div id="client_form" >
        <h2><?=T_("Agent")?></h2>
        <p class="blockintro"><?=T_("Select the application to link to the new agent")?></p>
        <div class="block">
          <dl>          	
            <!-- Client -->
            <dt class="required"><label for="agent[client]"><?=T_("Application")?>:</label></dt>
            <dd>
            	<select name="agent[client]" onchange="newvalue=appArr[this.options[this.selectedIndex].value]; document.getElementById('dis_extension').value=newvalue; document.getElementById('agent[extension]').value=newvalue;">
            		<?=$appOpt?>
              </select>
              <span id="clientErr"></span>
            </dd>
            <!-- Extension -->
            <dt class="required"><label for="agent[client]"><?=T_("Application")?>:</label></dt>
            <dd>
            	<input type="text" size="25" maxlength="255" id="dis_extension" value="<?=$extension?>" disabled="disabled" /></dd>
            	<input type="hidden" size="25" maxlength="255" id="agent[extension]" name="agent[extension]" value="<?=$extension?>" /></span>
            </dd>
            <!-- Username -->
            <dt class="required"><label for="agent[username]"><?=T_("Username")?>:</label></dt>
            <dd><input type="text" size="25" maxlength="255" id="agent[username]" name="agent[username]" value="<?=$username?>" /><span id="usernameErr"></span></dd>
            <!-- Password -->
            <dt class="required"><label for="agent[password]"><?=T_("Password")?>:</label></dt>
            <dd><input type="password" size="25" maxlength="255" id="agent[password]" name="agent[password]" value="<?=$password?>" /><span id="passwordErr"></span></dd>    
          </dl>
          <!-- Joined Queues -->
          <?=$joined_html?>
        </div>
      </div>        
      <div class="action">
        <?if ($_GET["id"]!="") {?><input type="hidden" name="agent[id]" value="<?=$_GET['id']?>" /><?}?>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
      <!--
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Annulla" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Salva" />
       -->
      </div>
    </form>
  </div>  
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="agents";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
  
?>

